// 使用统一配置 - 使用orderHttp实例（聊天功能可能与订单服务集成）
import { orderHttp as http } from './config';

export interface PageInfo<T> {
  list: T[];
  total: number;
  pageNum: number;
  pageSize: number;
}

// 聊天群组接口
export interface ChatGroup {
  id: number | null;
  createTime: string | null;
  updateTime: string | null;
  relaOrderId: number | null;
  name: string | null;
  type: string | null; // 'order' | 'customer_service' | 'notification'
  lastMessage: string | null;
  lastMessageTime: string | null;
  unreadCount: number | null;
  members: number | null;
  color: string | null;
  shopId: number | null;
  userId: number | null;
}

// 聊天消息接口
export interface ChatMessage {
  id: number | null;
  createTime: string | null;
  updateTime: string | null;
  relaGroupId: number | null;
  sender: string | null;
  senderType: string | null; // 'user' | 'shop' | 'rider' | 'system'
  content: string | null;
  messageType: string | null; // 'text' | 'image' | 'file' | 'system'
  timestamp: number | null;
  isRead: boolean | null;
}

// 标准接口一: 根据ID查询群组
export const selectGroupById = (id: number | null) => {
  return http.get<ChatGroup>(`/chat/group/${id}`);
};

// 标准接口二: 分页查询全部群组
export const selectAllGroups = (pageNum = 1, pageSize = 10) => {
  return http.get<PageInfo<ChatGroup>>('/chat/groups', {
    params: { pageNum, pageSize }
  });
};

// 标准接口三: 新增群组
export const insertGroup = (pojo: ChatGroup) => {
  return http.post<ChatGroup>('/chat/group', pojo);
};

// 标准接口四: 删除群组
export const deleteGroupById = (id: number) => {
  return http.delete<ChatGroup>(`/chat/group/${id}`);
};

// 标准接口五: 更新群组
export const updateGroup = (id: number | null, pojo: ChatGroup) => {
  return http.put<ChatGroup>(`/chat/group/${id}`, pojo);
};

// 扩展接口: 根据用户ID查询群组
export const selectGroupsByUserId = (userId: number, pageNum = 1, pageSize = 10) => {
  return http.get<PageInfo<ChatGroup>>(`/chat/groups/user/${userId}`, {
    params: { pageNum, pageSize }
  });
};

// 扩展接口: 根据订单ID查询群组
export const selectGroupByOrderId = (orderId: number) => {
  return http.get<ChatGroup>(`/chat/group/order/${orderId}`);
};

// 消息相关接口
// 根据群组ID查询消息
export const selectMessagesByGroupId = (groupId: number, pageNum = 1, pageSize = 50) => {
  return http.get<PageInfo<ChatMessage>>(`/chat/messages/group/${groupId}`, {
    params: { pageNum, pageSize }
  });
};

// 发送消息
export const sendMessage = (message: Partial<ChatMessage>) => {
  return http.post<ChatMessage>('/chat/message', message);
};

// 标记消息为已读
export const markMessageAsRead = (messageId: number) => {
  return http.put<ChatMessage>(`/chat/message/${messageId}/read`);
};

// 标记群组所有消息为已读
export const markGroupMessagesAsRead = (groupId: number) => {
  return http.put<void>(`/chat/group/${groupId}/read`);
};

// 创建订单聊天群组
export const createOrderChatGroup = (orderData: {
  orderId: number;
  userId: number;
  shopId: number;
  shopName: string;
}) => {
  return http.post<ChatGroup>('/chat/group/order', orderData);
}; 